/**
 * Add new method to tabs to delete all open tabs....
 */
$.extend($.ui.tabs.prototype, { 
    removeAll: function() { 
        for (var i = this.length() - 1; i >= 0; i--) { 
            this.remove(i); 
        }
        
        /**
         * Remove all rico Elements
         */
        $('div.ricoMenu').parent().parent().parent().parent().parent().remove();
        $('table.ricoCalTab').parent().parent().parent().parent().parent().parent().remove();
        $('div.ricoTree').parent().parent().parent().parent().parent().parent().remove();
        $('td.ricoLG_editDiv').parent().parent().parent().parent().remove();
        $('.ricoLG_editResponseDiv').remove();
    } 
}); 

/**
 * On widow resize.. resize all tables....
 */
$(window).resize(function() {
	// Loop over each value in the tables array.
	$.each(ricoTables, function(index, value) {
		try{
			// resize rico table
			//value.resizeWindow();
		}catch(error){
			alert(error);
		}
	});
});


function serializeForm(formId){
	var text = $("#"+formId).serialize();
};

function defaultCallback(data){
	try{
		// asdfs
	}catch(e){
	}
}

function getDateString(){
	var dateString = "--------";
	try {
		var mydate = new Date();
		dateString = "" + mydate.getFullYear()
				+ mydate.getMonth() + mydate.getDay() + mydate.getHours()
				+ mydate.getSeconds() + mydate.getUTCMilliseconds();
	} catch (e) {
	}
	return dateString;
}




function sendAjaxRequest(url, parameters, callback, dataType) {
	SwiftUI.sendAjaxRequest(url, parameters, callback, dataType);
}

function getUrlVars()
{
    return SwiftUI.getUrlVars();
}


function isLoggedIn(){
	return false;
}
var count = 0;

function getKeys(){
	SwiftUI.log("In Get keys");
	$.jCryption.getKeys("services/securityHandler?generateKeypair=true&dateString="+new Date().getTime(),function(receivedKeys) {
		keys = receivedKeys;
		// $("#toEncrypt").attr("disabled",false);
		// $("#encrypt").attr("disabled",false);
		// $("#status").html('<span style="font-size: 16px;">Ready to
		// encrypt</span>');
		
		/**
		 * If user is already assigned value then he came from post request so directly show body
		 */
		if(mediUser == ""){
			createLoginDialog();
		    
		    if(!isLoggedIn()){
		    	openLoginBox();
		    }
		} else{
			createLoginDialog();
			initializeLayout();
			loadBody();
			$("#login_status").empty();
			$("#userId_content").empty();
			$("#userId_content").append(externalId);
	    }
	    
	    $(".bubbleInner").everyTime(30000,function(i){
			getLogs();
		})			
		
	});
}

function getLogs(){
	//return;
	$.ajax({
		  url: "services/process/status?count="+count+"&clientName="+identifier+ "&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword+"&identifier="+identifier,
		  dataType:'html',
		  cache: false,
		  success: function(html){
			// Put the chat contents in the top right of the conversation.
			$(".bubbleInner").empty();
			try{
				$(".bubbleInner").append(html);
			}catch(e){
				//alert(e);
			}
		  }
		});
		count = count + 1;
}


function showHints(toggle) {
	if (document.getElementById) {
		document.getElementById('hints').style.display = toggle ? 'block':'none';
	}
}

function createLoginDialog(){
	//Getting the variable's value from a link 
	var loginBox = "#login_dialog";
	
	//Fade in the Popup
	$(loginBox).fadeIn(300);
	
	//Set the center alignment padding + border see css style
	var popMargTop = ($(loginBox).height() + 24) / 2; 
	var popMargLeft = ($(loginBox).width() + 24) / 2; 
	
	$(loginBox).css({ 
		'margin-top' : -popMargTop,
		'margin-left' : -popMargLeft
	});
	
	// Add the linkwithweb_mask to body
	$('body').append('<div id="linkwithweb_mask"></div>');
	$('#linkwithweb_mask').fadeIn(300);
	
	
	// When clicking on the button close or the linkwithweb_mask layer the popup closed
	if(false){
		$('a.close, #linkwithweb_mask').live('click', function() { 
			$('#linkwithweb_mask , .linkwithweb_login-popup').fadeOut(300 , function() {
				$('#linkwithweb_mask').remove();  
			});
		});
	}
	
	
	if(false){
	    loginDialog = $( "#login_dialog" ).dialog({ closeOnEscape: false,
			modal: true,
			draggable: false,
			resizable: false,
			width: $(window).width(),
			height: $(window).height(),
			open: function(event, ui) {
						$(this).closest('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
						$(this).closest('.ui-dialog').find('.ui-dialog-titlebar').hide();
			} 
	    });
	    loginDialog.dialog( "close" );
	}
    
    
    $("#login_button").click(function() {
    	try{
    		mediUser = $("#login_email").val();
    		mediPassword = $("#login_password").val();
    	}catch(e){
    		alert(e);
    	}
    	if(mediEncryptedPassword == ""){
	    	$.jCryption.encrypt(mediPassword,keys,function(encrypted) {
	    		mediEncryptedPassword = encrypted;
	    		submitLoginRequest();
	    	});
    	}else{
    		submitLoginRequest();
    	}
    });
}


function submitLoginRequest(){
	sendAjaxRequest("services/securityHandler", {requestMode: 'login',mediUser: mediUser,mediPass :mediEncryptedPassword,uniqueTimestamp:new Date().getTime()}, function(data){
		if(data.length >0) {
			if(data=="true" || data==true){
				$("#login_status").empty();
				$("#userId_content").empty();
				$("#userId_content").append(mediUser);
				closeLoginBox();
				initializeLayout();
				loadBody();
			}else{
				mediUser = "";
				mediPassword = "";
				mediEncryptedPassword = "";
				$("#login_status").append("Invalid username or password!!");
			}
		}
	});	
}

function logout(){
	mediUser = "";
	mediPassword = "";
	mediEncryptedPassword = "";
	openLoginBox();
}

/**
 * To open Login Dialog
 */
function openLoginBox(){
	$('#processing-form').dialog('close');
	
	$("#login_password").keyup(function(event){
	    if(event.keyCode == 13){
	        $("#login_button").click();
	    }
	});
	
	// $("#cover").show();
    // $( "#login_dialog" ).dialog( "open" );
}

/**
 * To close Login Dialog
 */
function closeLoginBox(){
	$('#linkwithweb_mask , .linkwithweb_login-popup').fadeOut(300 , function() {
		$('#linkwithweb_mask').remove();  
	});
	
	if(false){
		$( "#login_dialog" ).dialog( "close" );
		$("#cover").hide();
	}
}


function loadBody(){
	//$('#logWindow').corner();
	$('#dbDisconnectBtn').attr("disabled", "disabled");
	if(mediUser.indexOf("admin") != -1){
		$('#generateReportsConnectBtn').removeAttr("disabled");
		$('#closeAllReportsDisconnectBtn').removeAttr("disabled");
	}else{
		$('#generateReportsConnectBtn').attr("disabled", "disabled");
		$('#closeAllReportsDisconnectBtn').attr("disabled", "disabled");
	}
	
	isAdmin = getUrlVars()["isAdmin"];
	if(isAdmin == undefined){
		isAdmin = "false";
	}else{
		isAdmin = "true";
	}

	
	var isDemoUser = false;
	if(mediUser == "provider" || mediUser == "consumer"){
		isDemoUser = true;
	}
	
	//alert("Url---   :"+$("#menu-grid").jqGrid('getGridParam', 'url'));
	if(!isDemoUser){
		if($("#menu-grid").jqGrid('getGridParam', 'url') == "" || $("#menu-grid").jqGrid('getGridParam', 'url') == undefined){
		
			$("#menu-grid").jqGrid({
		        url: "services/menuController?mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword+"&identifier="+identifier+"&isAdmin="+isAdmin+"&uniqueString="+(new Date().getTime()),
		        datatype: "xml",
		        height: "auto",
		        pager: '#gridPager',
		        loadui: "disable",
		        colNames: ["id","Menu","url"],
		        colModel: [
		            {name: "id",width:0,hidden:true, key:true},
		            {name: "menu", width:250, resizable: false, sortable:false},
		            {name: "url",width:0,hidden:true}
		        ],
		        treeGrid: true,
				//caption: "Adminstration",
		        ExpandColumn: "menu",
		        autowidth: true,
		        //width: 180,
		        rowNum: 200,
		        ExpandColClick: true,
		        treeIcons: {leaf:'ui-icon-document-b'},
		        onSelectRow: function(rowid) {
		        	if(isConnected == "false"){
		        		alert("Please connect to DB before accessing");
		        		return;
		        	}
		        	
		        	var treedata = $("#menu-grid").jqGrid('getRowData',rowid);
		        	if(treedata.isLeaf=="true") {
		        		SwiftUI.getPerspective().loadOrSelectTab("center",treedata.menu,treedata.url);
		        	}
		        	
		        }
		    });
			
			jQuery("#menu-grid").jqGrid('navGrid','#gridPager',{add:false,del:false,edit:false,position:'right',search:false});
		}else{
			var newUrl = "services/menuController?mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword+"&identifier="+identifier+"&isAdmin="+isAdmin+"&uniqueString="+(new Date().getTime());
		
			try{
				maintab.tabs('removeAll');
			}catch(e){
			}
			
			try{
				jQuery("#menu-grid").jqGrid('setGridParam',{url:newUrl,page:1});
				jQuery("#menu-grid").trigger("reloadGrid");
			}catch(e){
			}
		}
	}else{
		// Commented out old menu to add new menu
	/***
	 * Adding JSTree code to create menu
	 */
		//constructMenu();
		loadMenuFromUrl("accordianMenu.html");
	}
	
	
	//jQuery("#menu-grid").setGridParam({url : newUrl}).trigger("reloadGrid");
	//$("#menu-grid").trigger("reloadGrid");
	
    $('#generateReportsConnectBtn').click(function() {
    	generateReportsConnectBtn();
    });
    
    $('#closeAllReportsDisconnectBtn').click(function() {
    	//$('#dbConnectBtn').removeAttr("disabled");
    	maintab.tabs('removeAll'); 
    });
    
    //SwiftUI.createUploadComponent("test_fileUpload");
    //SwiftUI.createRichTextEditor("test_textarea");
}

/**
 * @param url
 * @return
 */
function loadMenuFromUrl(url){
	$("#menu-grid").load(url,function(){
		$("#requestAnAppointment").click(function() {
			var st = "#requestAnAppointmentTab";
			if($(st).html() != null ) {
				maintab.tabs('select',st);
			} else {
				var url  = "services/scheduler/events/eventscheduler?schedulerId=Doctors&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword+"&identifier="+identifier+"&isAdmin="+isAdmin+"&uniqueString="+(new Date().getTime());
				
				maintab.tabs('add',st, "DocAppointment");
				$(st,"#swiftui_center_window_tabs").load(url);
				//$(st,"#swiftui_center_window_tabs").load(url);
			}
	    });
	});
}


function refreshTable(reportName){
	var tabId = $("#"+reportName+"_outerDiv").parents("div.ui-tabs-panel").attr("id");
	ricoTables[tabId].buffer.fetch(-1);
}


/**
 * To connect to Database
 */
function generateReportsConnectBtn(){
	sendAjaxRequest("services/v1/generateReports",{}, 
	function(data){
		if(data.length >0) {
			if(data=="success" || data==true){
				//closeLoginBox();
				//loadBody();
				//$('#dbDisconnectBtn').removeAttr("disabled");
				//isConnected = "true";
				$("#menu-grid").trigger("reloadGrid");
				//$('#dbConnectBtn').attr("disabled", "disabled");
				alert("Successfully Generated Reports...");
			}else{
				alert("Unable to connect to DB");
			}
		}
	});	
}


//$("#bofa_demo_jstree_outerDiv").parents("div.ui-tabs-panel").attr("id")
function assignTabToGrid(reportName,grid){
	var tabId = $("#"+reportName+"_outerDiv").parents("div.ui-tabs-panel").attr("id");
	ricoTables[tabId] = grid;
}


/**
 * Intitialize layout for body
 * @return
 */
function initializeLayout(){
	// Theme switcher
	$('#themeswitcher').themeswitcher();
	
	$(".ui-layout-west").show();
	$(".ui-layout-east").show();
	$(".ui-layout-north").show();
	$(".ui-layout-south").show();
	$("#mainContent").show();
	
	// create the OUTER LAYOUT
	outerLayout = $("body").layout( layoutSettings_Outer );

	/*******************************
	 ***  CUSTOM LAYOUT BUTTONS  ***
	 *******************************
	 *
	 * Add SPANs to the east/west panes for customer "close" and "pin" buttons
	 *
	 * COULD have hard-coded span, div, button, image, or any element to use as a 'button'...
	 * ... but instead am adding SPANs via script - THEN attaching the layout-events to them
	 *
	 * CSS will size and position the spans, as well as set the background-images
	 */

	// BIND events to hard-coded buttons in the NORTH toolbar
	//outerLayout.addToggleBtn( "#tbarToggleNorth", "north" );
	//outerLayout.addOpenBtn( "#tbarOpenSouth", "south" );
	//outerLayout.addCloseBtn( "#tbarCloseSouth", "south" );
	//outerLayout.addPinBtn( "#tbarPinWest", "west" );
	//outerLayout.addPinBtn( "#tbarPinEast", "east" );

	// save selector strings to vars so we don't have to repeat it
	// must prefix paneClass with "body > " to target ONLY the outerLayout panes
	var westSelector = "body > .ui-layout-west"; // outer-west pane
	var eastSelector = "body > .ui-layout-east"; // outer-east pane

	 // CREATE SPANs for pin-buttons - using a generic class as identifiers
	$("<span></span>").addClass("pin-button").prependTo( westSelector );
	$("<span></span>").addClass("pin-button").prependTo( eastSelector );
	// BIND events to pin-buttons to make them functional
	outerLayout.addPinBtn( westSelector +" .pin-button", "west");
	outerLayout.addPinBtn( eastSelector +" .pin-button", "east" );

	 // CREATE SPANs for close-buttons - using unique IDs as identifiers
	$("<span></span>").attr("id", "west-closer" ).prependTo( westSelector );
	$("<span></span>").attr("id", "east-closer").prependTo( eastSelector );
	// BIND layout events to close-buttons to make them functional
	outerLayout.addCloseBtn("#west-closer", "west");
	outerLayout.addCloseBtn("#east-closer", "east");



	/* Create the INNER LAYOUT - nested inside the 'center pane' of the outer layout
	 * Inner Layout is create by createInnerLayout() function - on demand
	 *
		innerLayout = $("div.pane-center").layout( layoutSettings_Inner );
	 *
	 */


	// DEMO HELPER: prevent hyperlinks from reloading page when a 'base.href' is set
	$("a").each(function () {
		var path = document.location.href;
		if (path.substr(path.length-1)=="#") path = path.substr(0,path.length-1);
		if (this.href.substr(this.href.length-1) == "#") this.href = path +"#";
	});
	
	


	SwiftUI.getPerspective().getTabHandles().center.bind('tabsselect', function(event, ui) {
	    // Objects available in the function context:
	    //ui.tab     // anchor element of the selected (clicked) tab
	    //ui.panel   // element, that contains the selected/clicked tab contents
	    //ui.index   // zero-based index of the selected (clicked) tab
        try{
        	try{
				ricoTables[ui.tab.hash.replace("#","")].resizeWindow();
			}catch(error){
			}
    		$.validationEngine.closePrompt(".formError",true)
        }catch(e){
        }
	});
	
}


/**
 * 
 * @return
 */
function constructMenu(){
	//alert("In construct menu");
	var menuUrl = "services/jsTreeData?mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword+"&identifier="+identifier+"&isAdmin="+isAdmin+"&uniqueString="+(new Date().getTime());
	
	
	
		$("#menu-grid")
			.bind("before.jstree", function (e, data) {
				//$("#alog").append(data.func + "<br />");
			})
			.jstree({ 
				// List of active plugins
				"plugins" : [ 
					"themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys"
					//,"contextmenu" 
				],

				// I usually configure the plugin that handles the data first
				// This example uses JSON as it is most common
				"json_data" : { 
					// This tree is ajax enabled - as this is most common, and maybe a bit more complex
					// All the options are almost the same as jQuery's AJAX (read the docs)
					"ajax" : {
						// the URL to fetch the data
						"url" : menuUrl,
						// the `data` function is executed in the instance's scope
						// the parameter is the node being loaded 
						// (may be -1, 0, or undefined when loading the root nodes)
						"data" : function (n) { 
							// the result is fed to the AJAX request `data` option
							return { 
								"operation" : "get_children", 
								"id" : n.attr ? n.attr("id").replace("node_","") : 1 
							}; 
						}
					}
				},
				// Configuring the search plugin
				"search" : {
					// As this has been a common question - async search
					// Same as above - the `ajax` config option is actually jQuery's AJAX object
					"ajax" : {
						"url" : menuUrl,
						// You get the search string as a parameter
						"data" : function (str) {
							return { 
								"operation" : "search", 
								"search_str" : str 
							}; 
						}
					}
				},
				// Using types - most of the time this is an overkill
				// read the docs carefully to decide whether you need types
				"types" : {
					// I set both options to -2, as I do not need depth and children count checking
					// Those two checks may slow jstree a lot, so use only when needed
					"max_depth" : -2,
					"max_children" : -2,
					// I want only `drive` nodes to be root nodes 
					// This will prevent moving or creating any other type as a root node
					"valid_children" : [ "drive" ],
					"types" : {
						// The default type
						"default" : {
							// I want this type to have no children (so only leaf nodes)
							// In my case - those are files
							"valid_children" : "none",
							// If we specify an icon for the default type it WILL OVERRIDE the theme icons
							"icon" : {
								"image" : "assets/jstree/images/file.png"
							},
							"start_drag" : false,
							"move_node" : false
						},
						// The `folder` type
						"folder" : {
							// can have files and o['ther folders inside of it, but NOT `drive` nodes
							"valid_children" : [ "default", "folder" ],
							"icon" : {
								"image" : "assets/jstree/images/folder.png"
							},
							"start_drag" : false,
							"move_node" : false
						},
						// The `drive` nodes 
						"drive" : {
							// can have files and folders inside, but NOT other `drive` nodes
							"valid_children" : [ "default", "folder" ],
							"icon" : {
								"image" : "assets/jstree/images/root.png"
							},
							// those prevent the functions with the same name to be used on `drive` nodes
							// internally the `before` event is used
							"start_drag" : false,
							"move_node" : false,
							"delete_node" : false,
							"remove" : false
						}
					}
				},
				// UI & core - the nodes to initially select and open will be overwritten by the cookie plugin

				// the UI plugin - it handles selecting/deselecting/hovering nodes
				"ui" : {
					// this makes the node with ID node_4 selected onload
					"initially_select" : [ "Administration" ]
				},
				// the core plugin - not many options here
				"core" : { 
					// just open those two nodes up
					// as this is an AJAX enabled tree, both will be downloaded from the server
					"initially_open" : [ "Administration" ] 
				}
			});
			
			
			/**
			 
			.bind("create.jstree", function (e, data) {
				$.post(
					menuUrl, 
					{ 
						"operation" : "create_node", 
						"id" : data.rslt.parent.attr("id").replace("node_",""), 
						"position" : data.rslt.position,
						"title" : data.rslt.name,
						"type" : data.rslt.obj.attr("rel")
					}, 
					function (r) {
						if(r.status) {
							$(data.rslt.obj).attr("id", "node_" + r.id);
						}
						else {
							$.jstree.rollback(data.rlbk);
						}
					}
				);
			})
			.bind("remove.jstree", function (e, data) {
				data.rslt.obj.each(function () {
					$.ajax({
						async : false,
						type: 'POST',
						url: menuUrl,
						data : { 
							"operation" : "remove_node", 
							"id" : this.id.replace("node_","")
						}, 
						success : function (r) {
							if(!r.status) {
								data.inst.refresh();
							}
						}
					});
				});
			})
			.bind("rename.jstree", function (e, data) {
				$.post(
						menuUrl, 
					{ 
						"operation" : "rename_node", 
						"id" : data.rslt.obj.attr("id").replace("node_",""),
						"title" : data.rslt.new_name
					}, 
					function (r) {
						if(!r.status) {
							$.jstree.rollback(data.rlbk);
						}
					}
				);
			})
			.bind("move_node.jstree", function (e, data) {
				data.rslt.o.each(function (i) {
					$.ajax({
						async : false,
						type: 'POST',
						url: menuUrl,
						data : { 
							"operation" : "move_node", 
							"id" : $(this).attr("id").replace("node_",""), 
							"ref" : data.rslt.cr === -1 ? "-1" : data.rslt.np.attr("id").replace("node_",""), 
							"position" : data.rslt.cp + i,
							"title" : data.rslt.name,
							"copy" : data.rslt.cy ? 1 : 0
						},
						success : function (r) {
							if(!r.status) {
								$.jstree.rollback(data.rlbk);
							}
							else {
								$(data.rslt.oc).attr("id", "node_" + r.id);
								if(data.rslt.cy && $(data.rslt.oc).children("UL").length) {
									data.inst.refresh(data.inst._get_parent(data.rslt.oc));
								}
							}
							$("#analyze").click();
						}
					});
				});
			});

			 * 
			 */
		//$("#menu-grid").jstree('refresh',-1);
}

